package com.skytech.component.monitor.enterprise_data_monitoring;

import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AnHuiService implements CrawlerScript {

    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;


    private static final Logger log = LoggerFactory.getLogger(AnHuiService.class);
    private static final String province = "安徽";

    public void start() {

        ChromeDriver driver = chromeBrowser.getChromeDriver();
        try {
            driver.get("http://www.aepb.gov.cn:8080/WRYJG/STZXGK/iframe2.aspx");//打开网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            partClickNext(driver);
        } catch (Exception e) {
            log.error("{}--网页打开失败--{}", driver.getCurrentUrl(), e.getMessage());
        } finally {
            driver.quit();
            log.info("数据爬取结束");
        }
    }

    String html;

    private void partClickNext(ChromeDriver driver) {
        do {
            String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
            if (html != null) {
                if (html.equals(htmlNew)) {
                    log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                    return;
                }
            }
            html = htmlNew;
            Elements allElements = parse.getAllElements();
            Elements elementsCity = allElements.select("#form1 > ul:nth-child(6) > table > tbody tr:nth-child(n+2)");
            //List<JSONObject> jsonObjectList = new ArrayList<>();
            List<MonitorData> monitorDataList = new ArrayList<>();
            for (Element e : elementsCity) {
                //   JSONObject jsonObject = new JSONObject();
                MonitorData monitorData = new MonitorData();
                if (!e.equals(elementsCity.last())) {
                    monitorData.setId(UUID.randomUUID().toString());
                    monitorData.setProvince(province);
                    monitorData.setCompanyName(e.getElementsByTag("td").get(0).text());
                    monitorData.setPollutionType(e.getElementsByTag("td").get(1).text());
                    monitorData.setMonitorPoint(e.getElementsByTag("td").get(2).text());
                    monitorData.setMonitorInfo(e.getElementsByTag("td").get(3).text());
                    monitorData.setMonitorTime(e.getElementsByTag("td").get(6).text());
                    monitorData.setMonitorValue(e.getElementsByTag("td").get(7).text());
                    monitorData.setMonitorStandardValue(e.getElementsByTag("td").get(8).text());
                    monitorData.setOverproof(e.getElementsByTag("td").get(10).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    monitorDataList.add(monitorData);
                }

            }
            try {
                WebElement webElement = driver.findElementByXPath("//*[@id='AspNetPager2']/div[1]/a[12]");
                webElement.click();
                log.info("当前页--{}", driver.getCurrentUrl());
            } catch (Exception e) {
                log.error("点击下一页出错！--{}", e.getMessage());
                return;
            }
            saveDataUtil.saveTag(monitorDataList, province);

        } while (true);

    }
}
